package top.xiewenwen.musicvisualizer;

import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class MusicFragment extends Fragment {

    private Button but_play;
    private Button but_stop;
    private Button but_replay;
    private MediaPlayer mediaPlayer;
    private VisualizerInterface visualizerInterface;

    public MusicFragment(VisualizerInterface visualizerInterface){
        this.visualizerInterface = visualizerInterface;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mediaPlayer = MediaPlayer.create(requireContext(), R.raw.taimeili); // music_file 是你放在 res/raw 文件夹下的音乐文件

        View view = inflater.inflate(R.layout.fragment_music, container, false);
        but_play = view.findViewById(R.id.but_play);
        but_stop = view.findViewById(R.id.but_stop);
        but_replay = view.findViewById(R.id.but_replay);
        but_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start(); // 开始播放
                visualizerInterface.VisualizerGetSessionID(mediaPlayer.getAudioSessionId());
            }
        });
        but_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.pause();
                visualizerInterface.VisualizerStop(mediaPlayer.getAudioSessionId());
            }
        });
        but_replay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.seekTo(0);
                mediaPlayer.start();
            }
        });
        return view;
    }
}